package manageAbilitiesServlets;

import java.io.IOException;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import sessions.abilitiesSession.AbilitySessionRemote;

public class SuggestNewAbilityServlet extends HttpServlet {

	private static final long serialVersionUID = 1L;

	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		insertAbilitySuggestion(request, response);
	}

	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		insertAbilitySuggestion(request, response);
	}

	private void insertAbilitySuggestion(HttpServletRequest request,
			HttpServletResponse response) {
		int id;
		String suggestedName, suggestedDescription;
		try {
			Context jndiCtx = new InitialContext();
			AbilitySessionRemote abilitySession = (AbilitySessionRemote) jndiCtx
					.lookup("Progetto/AbilitySession/remote");

			suggestedName = (String) request.getParameter("suggestedName");
			suggestedDescription = (String) request
					.getParameter("suggestedDescription");
			if (abilitySession.checkIfAbilityNameIsNew(suggestedName,true)) {
				// nome non gia' usato
				id = abilitySession.insertAbilitySuggestion(suggestedName,
						suggestedDescription);
				if (id != 0)
					request.getSession().setAttribute("result", "suggested");
				else{
					request.getSession().setAttribute("result", "nameNotNew");
				}
			} else {
				// nome gia' usato
				request.getSession().setAttribute("result", "alreadyInserted");
			}
		} catch (NamingException e) {
			System.out.print("errore nella connessione remota");
			e.printStackTrace();
			request.getSession().setAttribute("result", "mistake");
		}
		try {
			response.sendRedirect("/ProgettoWeb/ManageAbilitiesForUser.html");
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}